import java.util.ArrayList;
import java.util.Comparator;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2022-09-29
 * Time: 23:58
 */
class Interval {
    int start;
    int end;
    Interval() { start = 0; end = 0; }
    Interval(int s, int e) { start = s; end = e; }
}
public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        ArrayList<Interval> res = new ArrayList<>();
        if(intervals.size() == 0) //去除特殊情况
            return res;
        intervals.sort(new Comparator<Interval>() {
            public int compare(Interval o1, Interval o2) {
                if (o1.start != o2.start) {
                    return o1.start - o2.start;
                } else {
                    return o1.end - o2.end;
                }
            }
        }); //按照区间⾸排序
        res.add(intervals.get(0)); //放⼊第⼀个区间
        int count = 0;
        for (int i = 1; i < intervals.size(); i++) {//遍历后续区间，查看是否与末尾有重叠
            Interval o1 = intervals.get(i);
            Interval origin = res.get(count);
            if (o1.start > origin.end) {
                res.add(o1);
                count++;
            } else { //区间有重叠，更新结尾
                res.remove(count);
                Interval s = new Interval(origin.start, o1.end);
                if (o1.end < origin.end) {
                    s.end = origin.end;
                }
                res.add(s);
            }
        }
        return res;
    }
}

